<template>
  <van-button
    :loading="followLoading"
    v-if="value"
    class="follow-btn"
    round
    size="small"
    @click="onFollow"
    >已关注</van-button
  >

  <van-button
    :loading="followLoading"
    v-else
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    size="small"
    icon="plus"
    @click="onFollow"
    >关注</van-button
  >
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'FollowUser',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    userId: {
      type: [Object, Number, String],
      required: true
    }
  },
  data () {
    return {
      followLoading: false
    }
  },
  created () {},
  mounted () {},
  methods: {
    async onFollow () {
      // 开启loading状态
      this.followLoading = true
      try {
        if (this.value) {
          // 已经关注，取消关注
          await deleteFollow(this.userId)
        } else {
          // 没有关注，添加关注
          await addFollow(this.userId)
        }
        // 更改显示视图
        this.$emit('input', !this.value)
      } catch (err) {
        let message = '操作失败，请重试'
        // 如果是自己就提示一下
        if (err.response && err.response.status === 400) {
          message = '你不能关注你自己！'
        }
        this.$toast(message)
      }
      // 执行完关闭loading状态
      this.followLoading = false
    }
  }
}
</script>

<style scoped lang="less"></style>
